package redis

import (
	"context"
	"regexp"
	"sort"
	"strconv"

	. "github.com/go-redis/redis/v8"
)

func initSentinelSlave(addr, name string) (rdb *Client, err error) {
	rdbSentinel := NewFailoverClient(&FailoverOptions{
		MasterName:    name,
		SentinelAddrs: []string{addr},
		Password:      Password(),
		DB:            0,
		SlaveOnly:     true,
	})

	_, err = rdbSentinel.Ping(context.Background()).Result()
	if err != nil {
		return nil, err
	}
	return rdbSentinel, nil
}

// 模糊匹配key，获取value
func ScanDataSentinel(addr, name string, keyPattern string, wait int) string {

	rdb, err := initSentinelSlave(addr, name)
	if err != nil {
		return "initSentinelSlave 失败: " + err.Error()
	}
	return ScanData(rdb, keyPattern, wait)
}

func initSentinel(addr, name string) (rdb *Client, err error) {
	rdbSentinel := NewFailoverClient(&FailoverOptions{
		MasterName:    name,
		SentinelAddrs: []string{addr},
		Password:      Password(),
		DB:            0,
	})

	_, err = rdbSentinel.Ping(context.Background()).Result()
	if err != nil {
		return nil, err
	}
	return rdbSentinel, nil
}

func GroupByClientSentinel(addr, name string) string {
	var result string
	var resultMap = make(map[string]int)

	type redisR struct {
		addr string
		num  int
	}
	var redisList = make([]*redisR, 0)

	rdb, err := initSentinel(addr, name)
	if err != nil {
		return "连接不上redis Sentinel"
	}
	defer rdb.Close()

	listClient := rdb.ClientList(context.Background()).Val()

	rex := regexp.MustCompile("id=.*addr=(.*?):.*\n")
	subMatchs := rex.FindAllStringSubmatch(listClient, -1) //匹配括号里的
	for _, v := range subMatchs {
		if _, ok := resultMap[v[1:][0]]; !ok {
			resultMap[v[1:][0]] = 0
		}
		resultMap[v[1:][0]]++
	}

	for k, v := range resultMap {
		a := &redisR{addr: k, num: v}
		redisList = append(redisList, a)
	}

	sort.SliceStable(redisList, func(i int, j int) bool {
		return redisList[i].num > redisList[j].num
	})

	// 已经按照索引排序
	for _, val := range redisList {
		res := val.addr + " :: " + strconv.Itoa(val.num)
		result += res + "\n"
	}
	return result
}
